package com.feihong.yw189.bluetooth.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.adpater.SearchBleAdapter;
import com.feihong.yw189.bluetooth.contral.ReadContralCenter;
import com.feihong.yw189.bluetooth.contral.WriteContralCenter;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.bluetooth.dialog.ToSetBtDialog;
import com.feihong.yw189.bluetooth.listener.ResultListener;
import com.feihong.yw189.bluetooth.listener.UpLoadListener;
import com.feihong.yw189.bluetooth.startreadcard.DjlmConnectUtils;
import com.feihong.yw189.bluetooth.utils.util.ConstantsValue;
import com.feihong.yw189.bluetooth.utils.util.ImageTools;
import com.feihong.yw189.bluetooth.utils.util.PrefUtils;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.Kaika.YiZhengModel;
import com.google.gson.Gson;
import com.kaer.sdk.bt.BtReadClient;
import com.kaeridcard.client.BtReaderClient;

import org.xutils.common.Callback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Set;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 搜索蓝牙
 * 张鹏
 * 2017.11.16
 */
@RuntimePermissions
public class SearchBlueActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private ListView lv_ble1;
    private ProgressBar pb_ble1;
    private BluetoothAdapter ba;

    private ArrayList<String> bleNameList1 = new ArrayList<>();
    private ArrayList<String> bleAddressList1 = new ArrayList<>();
    private SearchBleAdapter bleAdapter1;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    pb_ble1.setVisibility(View.GONE);
                    ba.stopLeScan(mLeScanCallback);
                    break;
                case 1:
                    ll_choose_bule.setVisibility(View.GONE);
                    ll_search_blue.setVisibility(View.VISIBLE);
                    // 已配对设备搜索
                    SearchBts();
//                    // 可用设备搜索
//                    scanLeDevice(true);
                    break;
                case 2:
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivity(intent);
                case 3:
                    ba.stopLeScan(mLeScanCallback);
                    break;
                case 4:
                    redSucBack(count);
                    break;
                case 5:
                    redSucBack(1001);
                    break;
                default:
                    break;
            }
        }
    };
    private BluetoothDevice remoteDevice;
    private LinearLayout ll_search_blue;
    private LinearLayout ll_choose_bule;
    private TextView tv_bule;
    private TextView tv_nfc;
    private TextView tv_cancle;
    private boolean isUpData = true;
    private boolean isRead = true;
    private int mType;
    private String orderSn = "";
    private String isTest = "";
    private DjlmConnectUtils djlmConnectUtils;
    private ReadContralCenter bleContralCenter;
    private MyUsualyDialog dialog;
    private BtReadClient mBtReadClient;

    private String bluetoohName = "";
    private String address = "";
    private String sex = "";
    private String id_num = "";
    private String nation = "";
    private String sign_office = "";
    private String name = "";
    private String sign_data = "";
    private String birth_year = "";
    private String birth_month = "";
    private String birth_day = "";
    private String filePhoto = "";
    private String idPath = "";
    private String to = "";
    private String from = "";
    private String born = "";
    private String photoHeard = "";

    private byte[] bytes;
    private ArrayList<String> phone = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 透明状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);
        setContentView(R.layout.activity_search_blue);
        initView();
        copyLibFile();

        isUpData = getIntent().getBooleanExtra("isUpData", true); // 需不需要上传身份证数据
        isRead = getIntent().getBooleanExtra("isRead", true); // true 读卡,false 写卡
        mType = getIntent().getIntExtra("writType", 0); // 0废卡重置 1写卡 2补卡
        orderSn = getIntent().getStringExtra("orderSn"); // 写卡订单号
        isTest = getIntent().getStringExtra("isTest"); // 要不要验证一证五户

        ba = BluetoothAdapter.getDefaultAdapter(); // 获取蓝牙对象

        dialog = new MyUsualyDialog(this, R.layout.wait_item);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(false);
        dialog.setOnKeyListener((dialogInterface, i, keyEvent) -> {
            if (djlmConnectUtils != null) {
                djlmConnectUtils.stopConnect();
            }
            finish();
            return true;
        });
    }

    @Override
    public void setTheme() {

        isDrakFont = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @NeedsPermission({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE})
    void searchBlue() {
        // 如果是KT8003就提前初始化所需
        mBtReadClient = BtReadClient.getInstance();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String krServerIp = PrefUtils.getString(SearchBlueActivity.this, ConstantsValue.KRFTserverIp, "115.28.2.173");
                String krAccount = PrefUtils.getString(SearchBlueActivity.this, ConstantsValue.KRFTaccount, "admin");
                String krPassword = PrefUtils.getString(SearchBlueActivity.this, ConstantsValue.KRFTpassword, "www.kaer.cn");
                String krftPort = PrefUtils.getString(SearchBlueActivity.this, ConstantsValue.KRFTport, "7443");

                int krPort = Integer.parseInt(krftPort);
                int result = mBtReadClient.init(SearchBlueActivity.this, krServerIp,
                        krPort, krAccount, getMD5(krPassword.getBytes()), true);
            }
        }).start();

        // 先判断是否有蓝牙设置 后判断蓝牙是否开启  若没有开启则请求开启蓝牙
        if (!App.getApp().getmClinet().isBluetoothOpened()) {
            mHandler.sendEmptyMessage(2);
        } else {
            mHandler.sendEmptyMessage(1);// 开始搜索蓝牙
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_bule:

                if (App.getApp().getmClinet().isBleSupported()) {

                    SearchBlueActivityPermissionsDispatcher.searchBlueWithCheck(this);
                } else {
                    showToast("本机没有蓝牙装置");
                }
                break;
            case R.id.tv_nfc:
                ll_choose_bule.setVisibility(View.GONE);
                ll_search_blue.setVisibility(View.GONE);
                bluetoothName = "NFC读卡";
                dialog.show();
                dialog.setWarningTxt(R.id.progress_layout_warning_tv, "NFC读卡中");
                new Thread(() -> {
                    djlmConnectUtils = new DjlmConnectUtils(SearchBlueActivity.this, ba, null,
                            "", "", bluetoothName, isUpData, new UpLoadListener() {
                        @Override
                        public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                                String nation, String sign_office, String name, String sign_data,
                                                String birth_year, String birth_month, String birth_day,
                                                Bitmap photo, String filePhoto, String idPath, String to,
                                                String from, String born, String photoHeard) {

                            saveValue(bluetoohName, address, sex, id_num, nation, sign_office, name,
                                    sign_data, birth_year, birth_month, birth_day, photo, filePhoto,
                                    idPath, to, from, born, photoHeard);
                            if (id_num != null && !TextUtils.isEmpty(id_num)) {
                                if ("1".equals(isTest)) {
                                    yanZheng(id_num);
                                } else {
                                    redSucBack(0);
                                }
                            } else {
                                ToastUtils.showShortToast(SearchBlueActivity.this, "身份证数据为空");
                                mHandler.sendEmptyMessage(5);
                            }

                        }

                        @Override
                        public void onErrUpLoad(final String err) {
//                        Intent intent = new Intent();
//                        intent.putExtra("errMsg", err);
//                        setResult(300, intent); // 失败返回300
                            runOnUiThread(() -> {
                                if ((dialog != null)) {
                                    dialog.dismiss();
                                }
                                djlmConnectUtils.stopConnect();
                                if (!TextUtils.isEmpty(err) && err.equals(DjlmConnectUtils.NFC_NO_OPEN_CODE)) {
                                    new AlertDialog.Builder(SearchBlueActivity.this, R.style.alert_dialog_auto_light)
                                            .setMessage("NFC功能未打开")
                                            .setPositiveButton("去打开", (dialog, which) -> {
                                                goToOPenNfc();
                                                dialog.dismiss();
                                            })
                                            .setNegativeButton("取消", (dialog, which) -> {
                                                dialog.dismiss();
                                                finish();
                                            })
                                            .setCancelable(false)
                                            .show();
                                } else {
                                    showToast(err);
                                    finish();
                                }
                            });
                        }
                    });
                    djlmConnectUtils.connect(new BtReaderClient(SearchBlueActivity.this), true);
                }).start();

                break;
            case R.id.tv_cancle:
                finish();
                break;
            default:
                break;
        }
    }

    private void goToOPenNfc() {
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        startActivity(intent);
        finish();
    }

    private ArrayList<String> bleNameList = new ArrayList<>();
    private ArrayList<String> bleAddressList = new ArrayList<>();

    /**
     * 搜索已配对蓝牙
     */
    public void SearchBts() {
        bleNameList = new ArrayList<>();
        bleAddressList = new ArrayList<>();
        Set<BluetoothDevice> pairedDevices = ba.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                bleNameList.add(device.getName());
                bleAddressList.add(device.getAddress());
            }
        }
        scanLeDevice(true);
    }

    private String strName = "";
    private String bleAddress = "";
    private int index = 0;
    private int setbt = 0;
    private boolean btFlag = false;

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        ll_search_blue.setVisibility(View.GONE); // 隐藏设备列表

        setbt = 1;
        mHandler.sendEmptyMessage(0);
        mHandler.sendEmptyMessage(3);
        strName = bleNameList1.get(position);
        bleAddress = bleAddressList1.get(position);
        setBleTag(strName);

        remoteDevice = ba.getRemoteDevice(bleAddress);
        if (isRead) {
            for (int i = 0; i < bleNameList.size(); i++) {
                if (bleNameList.get(i).contains(strName)) {
                    btFlag = true;
                }
            }
            // 包含"DJLM"并且是附近可用设备就直接读卡
            if (strName.contains("DJLM") && setbt == 1) {
                startReadCard(strName, bleAddress);
            } else {
                // 如果已配对设备里不包含该设备则去配对,否则直接读卡
                if (!btFlag) {
                    ToSetBtDialog toSetBtDialog = new ToSetBtDialog(SearchBlueActivity.this);
                    toSetBtDialog.show();
                } else {
                    startReadCard(strName, bleAddress);
                }
            }
        } else {
            startWriteCard(bleAddress);
        }
    }

    private void startWriteCard(String address) {

        WriteContralCenter writeContralCenter = new WriteContralCenter(SearchBlueActivity.this,
                ba, mType, index, orderSn, new ResultListener() {
            @Override
            public void result(int result) {

                if (mType == 1 && result == 0) {
                    // 如果是写卡并且写卡成功就要返回一个值表示需要刷新web页
                    Intent intent = new Intent();
                    intent.putExtra("backResult", result);
                    setResult(200, intent); // 写卡/补卡/废卡重置  返回200
                    finish();
                } else {
                    // 如果是补卡或者废卡重置,不管成功失败只需要关闭本界面就行
                    finish();
                }
            }
        });
        writeContralCenter.writeCardStart(address);
    }

    private void startReadCard(String strName, String bleAdd) {
        dialog.show();
        dialog.setWarningTxt(R.id.progress_layout_warning_tv, "蓝牙读卡中");
        // 创建控制中心调用连接方法
        // 将头像转为字节数组传递回去
        // Bitmap bitmap = ImageTools.byteToBitmap(bytes);// 将字节数组转化为图片
        // 成功返回100
        // 失败返回200
        bleContralCenter = new ReadContralCenter(SearchBlueActivity.this, ba, mBtReadClient, remoteDevice,
                strName, bleAdd, index, bluetoothName, isUpData,
                new UpLoadListener() {
                    @Override
                    public void onSucUpLoad(String bluetoohName, String address, String sex,
                                            String id_num, String nation, String sign_office,
                                            String name, String sign_data, String birth_year,
                                            String birth_month, String birth_day, Bitmap photo,
                                            String filePhoto, String idPath, String to, String from,
                                            String born, String photoHeard) {
                        runOnUiThread(() -> {
                            saveValue(bluetoohName, address, sex, id_num, nation, sign_office, name,
                                    sign_data, birth_year, birth_month, birth_day, photo, filePhoto,
                                    idPath, to, from, born, photoHeard);
                            if (id_num != null && !TextUtils.isEmpty(id_num)) {
                                if ("1".equals(isTest)) {
                                    yanZheng(id_num);
                                } else {
                                    redSucBack(0);
                                }
                            } else {
                                showErrorToast("身份证号为空");
                                mHandler.sendEmptyMessage(5);
                            }
                        });
                    }

                    @Override
                    public void onErrUpLoad(final String err) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (err != null && !TextUtils.isEmpty(err)) {
                                    showErrorToast(err);
                                }
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
                                finish();
                            }
                        });

                    }
                });
        bleContralCenter.connectBle();
    }

    private void saveValue(String bluetoohName, String address, String sex, String id_num,
                           String nation, String sign_office, String name, String sign_data,
                           String birth_year, String birth_month, String birth_day, Bitmap photo,
                           String filePhoto, String idPath, String to, String from, String born,
                           String photoHeard) {
        bytes = ImageTools.bitmapToBytes(photo);// 将头像转为字节数组传递回去
//                        Bitmap bitmap = ImageTools.byteToBitmap(bytes);// 将字节数组转化为图片
        SearchBlueActivity.this.bluetoohName = bluetoohName;
        SearchBlueActivity.this.address = address;
        SearchBlueActivity.this.sex = sex;
        SearchBlueActivity.this.id_num = id_num;
        SearchBlueActivity.this.nation = nation;
        SearchBlueActivity.this.sign_office = sign_office;
        SearchBlueActivity.this.name = name;
        SearchBlueActivity.this.sign_data = sign_data;
        SearchBlueActivity.this.birth_year = birth_year;
        SearchBlueActivity.this.birth_month = birth_month;
        SearchBlueActivity.this.birth_day = birth_day;
        SearchBlueActivity.this.filePhoto = filePhoto;
        SearchBlueActivity.this.idPath = idPath;
        SearchBlueActivity.this.to = to;
        SearchBlueActivity.this.from = from;
        SearchBlueActivity.this.born = born;
        SearchBlueActivity.this.photoHeard = photoHeard;
    }

    private void redSucBack(int value) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("bluetoohName", bluetoohName);
        bundle.putString("address", address);
        bundle.putString("sex", sex);
        bundle.putString("id_num", id_num);
        bundle.putString("nation", nation);
        bundle.putString("sign_office", sign_office);
        bundle.putString("name", name);
        bundle.putString("sign_data", sign_data);
        bundle.putString("birth_year", birth_year);
        bundle.putString("birth_month", birth_month);
        bundle.putString("birth_day", birth_day);
        bundle.putByteArray("photo", bytes);
        bundle.putString("filePhoto", filePhoto);
        bundle.putString("idPath", idPath);
        bundle.putString("to", to);
        bundle.putString("from", from);
        bundle.putString("born", born);
        bundle.putString("photoHeard", photoHeard);
        bundle.putInt("count", value);
        if (phone != null) {
            bundle.putSerializable("phoneList", (Serializable) phone);
        }
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent); // 成功返回100
        if (dialog != null) {
            dialog.dismiss();
        }
        finish();
    }

    private String bluetoothName;
    private int count = 0;  // 一证五户个数

    public void yanZheng(final String idNum) {
        App.getApp().getHttpTools().getYiZhengWuHu(idNum, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (activityIsDestory()) {
                    return;
                }
                Gson gson = new Gson();
                YiZhengModel yiZhengModel = gson.fromJson(result, YiZhengModel.class);

                if (yiZhengModel.getStatus() == 1) {
                    count = yiZhengModel.getData().getList().getCount();
                    phone = yiZhengModel.getData().getList().getPhone();
                    mHandler.sendEmptyMessage(4);
                } else {
                    ToastUtils.showShortToast(SearchBlueActivity.this, yiZhengModel.getInfo());
                    mHandler.sendEmptyMessage(5);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (activityIsDestory()) {
                    return;
                }
                showToast(getResources().getString(R.string.connect_sever_error_toast));
                mHandler.sendEmptyMessage(5);
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });

    }


    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bleNameList1.clear();
        bleAddressList1.clear();
        if (mLeScanCallback != null) {
            // 触发消失监听
            ba.stopLeScan(mLeScanCallback);
        }
        if (dialog != null) {
            dialog.dismiss();
        }
        // 断开读卡连接
        if (bleContralCenter != null) {
            bleContralCenter.disConnect();
        }
        if (djlmConnectUtils != null) {
            djlmConnectUtils.stopConnect();
        }
        mHandler.removeCallbacksAndMessages(null);
    }

    private static final long SCAN_PERIOD = 10000;

    public void scanLeDevice(final boolean enable) {
        bleNameList1 = new ArrayList<>();
        bleAddressList1 = new ArrayList<>();
        bleAdapter1 = new SearchBleAdapter(SearchBlueActivity.this, bleNameList1);
        lv_ble1.setAdapter(bleAdapter1);
        if (enable) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ba.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);
            ba.startLeScan(mLeScanCallback);
        } else {
            pb_ble1.setVisibility(View.GONE);
        }
    }

    /**
     * 搜索蓝牙(djlm)
     */
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pb_ble1.setVisibility(View.VISIBLE);
                            Boolean judge = false;
                            mHandler.sendEmptyMessageDelayed(0, 6000);
                            if (bleNameList1 != null && bleNameList1.size() > 0) {
                                if (bleNameList1.size() < 10) {
                                    if (device.getName() != null
                                            && !"null".equals(device.getName())
                                            && !TextUtils.isEmpty(device.getName())) {
                                        for (String s : bleNameList1) {
                                            if (s != null && !"null".equals(s) && !TextUtils.isEmpty(s)) {
                                                if (s.contains(device.getName())) {
                                                    judge = true;
                                                }
                                            }
                                        }
                                        if (!judge) {
                                            bleNameList1.add(device.getName());
                                            bleAddressList1.add(device.getAddress());
                                            bleAdapter1.notifyDataSetChanged();
                                        }
                                    }
                                } else {
                                    pb_ble1.setVisibility(View.GONE);
                                    ba.stopLeScan(mLeScanCallback);
                                }
                            } else {
                                if (device.getName() != null
                                        && !"null".equals(device.getName())
                                        && !TextUtils.isEmpty(device.getName())) {
                                    bleNameList1.add(device.getName());
                                    bleAddressList1.add(device.getAddress());
                                    bleAdapter1.notifyDataSetChanged();
                                }
                            }
                        }
                    });
                }
            };

    private void initView() {
        // 已配对
        ll_search_blue = (LinearLayout) findViewById(R.id.ll_search_blue); // 点击设备之后隐藏
        ll_choose_bule = (LinearLayout) findViewById(R.id.ll_choose_bule); // 点击设备之后隐藏

        tv_bule = (TextView) findViewById(R.id.tv_bule);
        tv_nfc = (TextView) findViewById(R.id.tv_nfc);
        tv_cancle = (TextView) findViewById(R.id.tv_cancle);
        tv_bule.setOnClickListener(this);
        tv_nfc.setOnClickListener(this);
        tv_cancle.setOnClickListener(this);

        // 附近可用
        lv_ble1 = (ListView) findViewById(R.id.lv_ble1);
        pb_ble1 = (ProgressBar) findViewById(R.id.pb_ble1);

        lv_ble1.setOnItemClickListener(this);
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SearchBlueActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE})
    void showCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获取蓝牙权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE})
    void denied() {
        showErrorDialog("权限不足", "您没有开启此应用的使用蓝牙权限。请到系统设置-->权限管理 开启蓝牙使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下蓝牙权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE})
    void askAgain() {
        showErrorDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启蓝牙使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下蓝牙权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    private void setBleTag(String bleStrName) {
        if (bleStrName.contains("KT8000")) {
            index = 1;
            bluetoothName = "卡尔KT8000读卡";
        } else if (bleStrName.contains("KT8003")) {
            index = 2;
            bluetoothName = "卡尔KT8003读卡";
        } else if (bleStrName.contains("SS")) {
            index = 3;
            bluetoothName = "神思读卡";
        } else if (bleStrName.contains("SR")) {
            index = 4;
            bluetoothName = "森锐读卡";
        } else if (bleStrName.contains("HOD")) {
            index = 5;
            bluetoothName = "恒鸿达读卡";
        } else if (bleStrName.contains("DJLM")) {
            index = 6;
            bluetoothName = "店家联盟读卡";
        } else if (bleStrName.contains("ST710")) {
            index = 7;
            bluetoothName = "信通读卡";
        } else if (bleStrName.contains("CVR")) {
            // 华视读卡
            index = 0;
            bluetoothName = "华视读卡";
        } else {
            // 华视读卡(华视读卡器名称不一致,无法规律化)
            index = 0;
            bluetoothName = "华视读卡";
        }
    }

    private void copyLibFile() {
        String path = Environment.getExternalStorageDirectory() + "/wltlib";
        String filename1 = path + "/" + "base.dat";
        String filename2 = path + "/" + "license.lic";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        try {
            if (!(new File(filename1)).exists()) {
                InputStream is = null;
                is = getApplicationContext().getResources().openRawResource(R.raw.base);
                int size = is.available();
                FileOutputStream fos = new FileOutputStream(filename1);
                byte[] buffer = new byte[8192];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
            } else {
            }
            if (!(new File(filename2)).exists()) {
                InputStream is = null;
                is = getApplicationContext().getResources().openRawResource(R.raw.license);
                int size = is.available();
                FileOutputStream fos = new FileOutputStream(filename2);
                byte[] buffer = new byte[8192];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
            } else {
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 卡尔KT8003 账号密码  加密方法
     */
    private String getMD5(byte[] source) {
        String s = null;
        char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
                'e', 'f'};
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(source);
            byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数，
            // 用字节表示就是 16 个字节
            char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
            // 所以表示成 16 进制需要 32 个字符
            int k = 0; // 表示转换结果中对应的字符位置
            for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
                // 转换成 16 进制字符的转换
                byte byte0 = tmp[i]; // 取第 i 个字节
                str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
                // >>> 为逻辑右移，将符号位一起右移
                str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
            }
            s = new String(str); // 换后的结果转换为字符串

        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }
}
